#pragma once

#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <sys/wait.h>

#define FILENAME "fifo"
#define PATH "."

#define ERR_EXIT(m)     \
    do  \
    {       \
        perror(m);  \
        exit(EXIT_FAILURE); \
    }while(0)   \

class NamedFifo
{
public:
    NamedFifo(const std::string& name, const std::string& path)
        :_name(name), _path(path)
    {
        _filename = _path + "/" + _name;

        int n = mkfifo(_filename.c_str(), 0666);
        if(n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "管道创建成功" << std::endl;
        }
    }

    ~NamedFifo()
    {
        int n = unlink(_filename.c_str());
        if(n < 0)
        {
            ERR_EXIT("unlink");
        }
        else
        {
            std::cout<< "管道删除成功" << std::endl;
        }
        
    }
private:
    std::string _name;
    std::string _path;
    std::string _filename;
};

class FileOper
{
public:
    FileOper(const std::string& name, const std::string& path)
        :_name(name), _path(path), _fd(-1)
    {
        _filename = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_filename.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open for read");
        }
        else
        {
            std::cout<< "打开" << _filename << "成功准备读" << std::endl;
        }
    }

    void OpenForWrite()
    {
        _fd = open(_filename.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open for write");
        }
        else
        {
            std::cout<< "打开" << _filename << "成功准备写" << std::endl;
        }
    }

    void Read()
    {
        while(true)
        {
            char buffer[1024];
            ssize_t number = read(_fd, buffer, sizeof(buffer) - 1);
            if(number > 0)
            {
                buffer[number] = 0;
                std::cout << "client say# " << buffer << std::endl;
            }
            else if(number == 0)
            {
                std::cout << "client quittt!" << std::endl;
                break;
            }
            else
            {
                ERR_EXIT("read");
                break;
            }
        }
    }

    void Write()
    {
        int cnt = 0;
        std::string message;
        int id = getpid();
        while(true)
        {
            std::cout << "Please Enter# ";
            getline(std::cin, message);
            message += ", message number" + std::to_string(cnt) + "-[" + std::to_string(id) + "]";
            write(_fd, message.c_str(), message.size());
        }
    }

    void Close()
    {
        if(_fd > 0)
            close(_fd);
    }

    ~FileOper()
    {

    }

private:
    std::string _name;
    std::string _path;
    std::string _filename;
    int _fd;
};
